import React, { useEffect, useState } from 'react'
import { useLocation, useNavigate } from "react-router-dom"
import type { MenuProps } from 'antd';
import { Menu, Layout } from 'antd';
import {
  DesktopOutlined,
  FileOutlined,
  PieChartOutlined,
  TeamOutlined,
  UserOutlined,
} from '@ant-design/icons';

const { Sider } = Layout;
const items: {
  key: string,
  icon: JSX.Element,
  label: string,
  children?: typeof items
}[] = [
  {
    key: 'user',
    icon: <UserOutlined />,
    label: '用户',
    children: [
      {
        key: '/user/about',
        icon: <TeamOutlined />,
        label: 'Tom',
      },
      {
        key: '/user/news2',
        icon: <TeamOutlined />,
        label: 'news2',
      }
    ]
  },
  {
    key: '/news',
    icon: <PieChartOutlined />,
    label: '最新',
  },
  {
    key: '/news24',
    icon: <DesktopOutlined />,
    label: '最好',
  },
  {
    key: '/news25',
    icon: <FileOutlined />,
    label: '最棒',
  },
]
const MyMenu: React.FC = () => {
  const currentRoute = useLocation()
  const [collapsed, setCollapsed] = useState(false);
  const navigator = useNavigate()
  const [openKeys, setOpenKeys] = useState<string[]>([])

  useEffect(() => {
    let firstOpenkey = ""
    for (let i=0;i<=items.length;i++) {
      if(items[i]?.children?.find(findkey)){
        firstOpenkey = items[i]?.key as string
        break;
      }
    }
    setOpenKeys([firstOpenkey])
  },[])
  const findkey = (item:{key:string}) => {
    return item.key === currentRoute.pathname
  }
  const goMenu = (e: { key: string }) => {
    console.log(e.key);
    navigator(`${e.key}`)
  }
  const onOpenChange: MenuProps['onOpenChange'] = (keys: string[]) => {
    setOpenKeys([keys[keys.length - 1]])
  };
  return (
    <>
      <Sider collapsible collapsed={collapsed} onCollapse={(value: boolean) => setCollapsed(value)}>
        <div className="logo-vertical" />
        <Menu
          theme="dark"
          defaultSelectedKeys={[currentRoute.pathname]}
          mode="inline" items={items}
          onOpenChange={onOpenChange}
          openKeys={openKeys}
          onClick={goMenu}
        />
      </Sider>
    </>
  )
}

export default MyMenu